package com.qianfeng.zw.meilishuo.utils;

import android.content.Context;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @Package com.qianfeng.zw.meilishuo.utils
 * @作 用:
 * @创 建 人: zhangwei
 * @日 期: 15/3/28 21:44
 * @修 改 人:
 * @日 期:
 */
public class Utils {

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String fileToStr(String path) {
        File file = new File(path);
        try {
            return new String(fileToBytes(file), "GB2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static byte[] fileToBytes(String path) {
        File file = new File(path);
        return fileToBytes(file);
    }


    /**
     * 讲文件转化成byte[]
     *
     * @param file
     * @return
     */
    public static byte[] fileToBytes(File file) {
        ByteArrayOutputStream out = null;
        FileInputStream stream = null;
        byte[] bytes = new byte[2 * 1024];
        int count = 0;
        try {
            stream = new FileInputStream(file);
            out = new ByteArrayOutputStream(1000);
            while ((count = stream.read(bytes)) != -1) {
                out.write(bytes, 0, count);
            }
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


}
